/**
 * @description  损益分布图（VAR分析）
 * @author zht
 */
import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { SecondHeaderC, XYAxisChartsC, QuickQueryC } from '../../../../comps';
import Color from '../../../../css/colors';
import _ from 'lodash';

class GainsAndLosses extends PureComponent {
  debtAndProfitColor = Color.debtAndProfit.background; // type为收益负债模式时，固定显示的颜色
  constructor() {
    super();
    this.state = {
      xAxis: [], //X轴数据
      series: [], //柱状图与正太分布数据
      toolData: [],
      type: false,
      isBox: false, //cheackbox是否展示
      date: '--',
    };
  }

  componentDidMount() {
    const { formData } = this.props;
    this.getData(formData);
    if ('benchMark' in formData) {
      this.setState({
        isBox: true,
      });
    }
  }

  UNSAFE_componentWillReceiveProps(nextProps) {
    const { formData } = nextProps;
    if (JSON.stringify(formData) !== JSON.stringify(this.props.formData)) {
      this.getData(formData);
      this.setState(
        {
          isBox: false,
        },
        () => this.changBox(formData),
      );
    }
  }

  changBox = (formData) => {
    if ('benchMark' in formData) {
      this.setState({
        type: false,
        isBox: true,
      });
    } else {
      this.setState({
        isBox: false,
      });
    }
  };

  //获取数据
  getData = (formData) => {
    const { confidenceLevel, endDate, horizonTime, portfolioId, benchMark } = formData;
    let id = '';
    'portfolioId' in formData ? (id = portfolioId) : (id = benchMark);
    this.props.dispatch({
      type: 'varAnalysisM/queryGainsAndLosses',
      payload: {
        confidenceLevel: confidenceLevel,
        endDate: endDate,
        horizonTime: horizonTime,
        portfolioId: id,
      },
      callback: (data) => {
        if (data && data.series.length && data.xAxis.length) {
          this.props.demo.getChildrenMsg(this, data.date);
          const series = this.querySeriesData(data);
          this.setState({
            xAxis: data.xAxis,
            xAxis1: data.xAxis1,
            series: series,
            date: data.date,
          });
        } else {
          this.setState({
            xAxis: [],
            xAxis1: [],
            series: [],
            date: '--',
          });
        }
      },
    });
  };
  //柱状图数据
  querySeriesData = (datas) => {
    let that = this;
    const newData = [];
    const newSeries = _.cloneDeep(datas.series);
    newSeries.map((item) => {
      if (item.name == '正态分布') {
        (item.type = 'area'), (item.smooth = true), (item.symbol = 'none');
      } else {
        this.setState({
          toolData: item.data,
        });
        item.data.map((i) => {
          newData.push(i.value);
        });
        item.data = newData;
        item.itemStyle = {
          normal: {
            color: function (params) {
              var date = datas.xAxis[params.dataIndex];
              var maxDate = datas.xAxis[datas.xAxis.length - 1];
              if (parseInt(date) >= 1 && parseInt(date) <= parseInt(maxDate)) {
                return that.debtAndProfitColor[0];
              } else {
                return that.debtAndProfitColor[1];
              }
            },
          },
        };
      }
    });
    return newSeries;
  };
  //组合/基准回调函数
  onChangeRadio = (e, type) => {
    const { formData } = this.props;
    if (!type) {
      this.setState({
        type: true,
      });
      return;
    }
    if (e == 'benchMark') {
      const formDatas = _.cloneDeep(formData);
      delete formDatas.portfolioId; //当选择基准时，删除组合id
      this.getData(formDatas);
    } else {
      this.getData(formData);
    }
  };

  //提示框显示内容
  toolTipFormat = (params) => {
    const { toolData } = this.state;
    let str = `<div >`;
    params.map((item, index) => {
      if (item.seriesName != '正态分布') {
        let yAxisIndex = -1;
        yAxisIndex = item.dataIndex;
        if (toolData[yAxisIndex]) {
          str += `<div>数量：${toolData[yAxisIndex].total}</div>`;
          toolData[yAxisIndex].list.map((ele) => {
            str += `<div style="display:flex;align-items:center">
                  ${ele.date}： ${ele.data}
                </div>`;
          });
        }
      }
    });
    str += '</div>';
    return str;
  };

  render() {
    const { xAxis, xAxis1, series, type, isBox } = this.state;

    return (
      <div>
        <SecondHeaderC
          title='损益分布图'
          Right={
            isBox ? (
              <QuickQueryC
                dataSource={[
                  { value: 'portfolioId', title: '组合' },
                  { value: 'benchMark', title: '基准' },
                ]}
                initialValue={'portfolioId'}
                onChange={(e) => this.onChangeRadio(e, type)}
              />
            ) : null
          }
        />
        <XYAxisChartsC
          series={series}
          xAxis={[xAxis1, xAxis]}
          height={400}
          type='bar'
          yAxisUnit={['概率分布(%)']}
          yAxisFormat={[(value) => value * 100]}
          // debtAndProfit={true}
          isShowLegent={false}
          toolTipFormat={this.toolTipFormat}
        />
      </div>
    );
  }
}
export default connect(({ gainsAndLossesM }) => ({
  gainsAndLossesM,
}))(GainsAndLosses);
